
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="公司名稱" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入公司名稱"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="拜訪交通" prop="travel">
        <el-input
          v-model="queryParams.travel"
          placeholder="请输入拜訪交通"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="創建人员" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入創建人员"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="拜訪時間" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="開始日期"
          end-placeholder="結束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


















    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          v-hasPermi="['system:visiting:add']"
          @click="handleAdd"
          >拜訪維護</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="CircleClose"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:visiting:delete']"
          >批量删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Close"
          v-if="queryParams.businessId && queryParams.businessId !== ''"
          @click="handleClose"
          >關閉</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      border
      :data="contactsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        :selectable="selectable"
        width="55"
        align="center"
      />
      <el-table-column
        label="公司名稱"
        align="center"
        prop="customerName"
        :show-overflow-tooltip="false"
      />
      <el-table-column
        label="拜訪記錄"
        align="center"
        prop="name"
        :show-overflow-tooltip="false"
      />
      <el-table-column
        label="拜訪交通"
        align="center"
        prop="travel"
        :show-overflow-tooltip="false"
      />
      <el-table-column
        label="拜訪時間"
        align="center"
        prop="visitTime"
        :show-overflow-tooltip="false"
      />
      <el-table-column
        label="創建人员"
        align="center"
        prop="nickName"
        :show-overflow-tooltip="false"
      />
      <el-table-column label="創建時間" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:visiting:update']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              v-if="scope.row.first !== 1"
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:visiting:delete']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form
        :rules="rules"
        ref="addclientele"
        :model="form"
        label-width="100px"
      >
        <el-form-item
          label="公司:"
          prop="businessId"
          v-if="!queryParams.businessId"
        >
          <el-select
            style="width: 100%"
            v-model="form.businessId"
            filterable
            placeholder="请选择公司名称"
            @change="handleCaseNameChange"
            clearable
          >
            <el-option
              v-for="item in companyData"
              :key="item.customerName"
              :label="item.customerName"
              :value="item.businessId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="拜訪內容:" prop="name">
          <el-input
            v-model="form.name"
            :rows="4"
            type="textarea"
            placeholder="請輸入拜訪內容"
          />
        </el-form-item>
        <el-form-item label="拜訪交通:" prop="travel">
          <el-select
            style="width: 100%"
            v-model="form.travel"
            placeholder="拜訪交通"
          >
            <el-option
              v-for="item in travel_tool"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="拜訪时间:" prop="visitTime">
          <el-date-picker
            v-model="form.visitTime"
            type="datetime"
            placeholder="选择拜访时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            :shortcuts="dateShortcuts"
         
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">確 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Auth">
import {
  addvisiting,
  listvisiting,
  delvisiting,
  updatevisiting,
} from "@/api/business/journal.js";

import {
  listbusinesscustomerName,
  getbusinessAndcase,
} from "@/api/business/add.js";
import { ref } from "vue";

const route = useRoute();
const { proxy } = getCurrentInstance();
const { travel_tool, business_source } = proxy.useDict("travel_tool");

const ids = ref([]);
const contactsList = ref([]);
const dateRange = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const multiple = ref(true);
const open = ref(false);
const total = ref(0);
const userIds = ref([]);
const title = ref("");
const form = ref({});
const companyData = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  businessId: route.params.Id,

  rules: {
    businessId: [{ required: true, message: "公司不能为空", trigger: "blur" }],
    name: [{ required: true, message: "拜訪內容不能为空", trigger: "blur" }],
    visitTime: [
      { required: true, message: "请选择拜访时间", trigger: "change" },
    ],
  },
});
const { rules } = toRefs(queryParams);

const dateShortcuts = [
  {
    text: "今天",
    value: new Date(),
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];

function reset() {
  form.value.name = "";
  form.value.businessId = route.params.Id || null;
  form.value.id = null;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

//添加联系人按钮
function submitForm() {
  proxy.$refs["addclientele"].validate((valid) => {
    if (valid) {
      // 合并数据
      const mergedData = { ...form.value };
      if (form.value.id != null) {
        updatevisiting(mergedData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addvisiting(mergedData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 处理业务数据响应
function handleBusinessResponse(response) {
  companyData.value = response.rows.map((item) => ({
    customerName: item.customerName,
    abbreviation: item.abbreviation,

    contactsVos: item.contactsVos,
    businessId: item.id,
  }));
}

/** 添加联系人 */
async function handleAdd() {
  try {
    reset();
    // 先获取数据
    const response = await getbusinessAndcase();
    handleBusinessResponse(response);
    // 数据获取成功后再打开对话框
    open.value = true;
    title.value = "添加拜访";
  } catch (error) {
    proxy.$modal.msgError("获取数据失败：" + error.message);
  }
}
/** 查询授权用户列表 */
function getList() {
  loading.value = true;
  listvisiting(proxy.addDateRange(queryParams, dateRange.value)).then((response) => {
    contactsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 返回按钮
function handleClose() {
  const obj = { path: "/business/business/add" };
  proxy.$tab.closeOpenPage(obj);
}

/** 修改角色 */
function handleUpdate(row) {
  form.value.name = row.name;
  form.value.businessId = row.businessId;
  form.value.id = row.id;
  form.value.firstname = row.name;
  form.value.travel=row.travel;
  form.value.visitTime = row.visitTime;
  open.value = true;
  title.value = "修改拜访记录";
}

//禁止选择first默认联系人
const selectable = (row) => ![1, 2].includes(row.first);
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  multiple.value = !selection.length;
}

/** 取消按钮 */
function cancel() {
  reset();
  open.value = false;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除为"' + id + '"的数据项?')
    .then(function () {
      return delvisiting(id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
// getbusinessAndcase().then((response) => {
//   handleBusinessResponse(response);
// });
</script>
